/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package communication;

import Exceptions.CloseTransportException;
import Exceptions.ReceiveTransportException;
import Exceptions.SendTransportException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author Dubos Romain
 * @author Oukherfellah Riad    
 */
public class Transport implements InterfaceTransport {

    private Socket s;
    ObjectOutputStream out;
    ObjectInputStream in;

    public Transport(Socket pS) throws IOException {
        this.s = pS;
        this.out = new ObjectOutputStream(s.getOutputStream());
        this.in = new ObjectInputStream(s.getInputStream());

    }

    public Transport(String host, int port) throws IOException {
        this.s = new Socket(host, port);
        this.in = new ObjectInputStream(s.getInputStream());
        this.out = new ObjectOutputStream(s.getOutputStream());
    }

    @Override
    public void envoyer(Object o) throws SendTransportException {
        try {
            out.writeObject(o);
        } catch (IOException ex) {
            throw new SendTransportException();
        }
    }

    @Override
    public Object recevoir() throws ReceiveTransportException {
        try {
            return in.readObject();
        } catch (IOException ex) {
            throw new ReceiveTransportException();
        } catch (ClassNotFoundException ex) {
            throw new ReceiveTransportException();
        }
    }

    @Override
    public void fermer() throws CloseTransportException {
        try {
            this.out.close();
            this.in.close();
            this.s.close();
        } catch (IOException e) {
            throw new CloseTransportException();
        }
    }
    
    public void setSocket(Socket pS){
        this.s=pS;
    }
}
